/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.graph;

import com.bayu.common.lib.CommonUtil;
import com.bayu.common.lib.RoundNumber;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import com.bayu.controller.MainController;
import com.bayu.services.dao.ListrikDao;
import com.bayu.services.entity.Listrik;
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberAxis3D;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author Bayu
 */
@Controller
public class ListrikGraph {
  private ListrikDao listrikDao;

  @Autowired
  private void setListrikDao(ListrikDao listrikDao){
      this.listrikDao = listrikDao;
  }

  @RequestMapping("/listrik.png")
  public void generateListrikGraph(OutputStream stream) throws Exception {
    Double min = 0.0D;
    Double max = 8000.0D;
    //boolean rotate = "rotate".equals(variation); // add ?variation=rotate to the URL to rotate the chart
    JFreeChart chart = listrikGraph("Mill Rp", "Unit Price(Rp)", "Month", "Mill. Rp",min,max);
    ChartUtilities.writeChartAsPNG(stream, chart, 1480,800);
  }

  public JFreeChart listrikGraph(String rowValue1,String rowValue2,String domainAxisLabel,String rangeAxisLabel,Double min,Double max) throws IOException{
       String tgl1="";
      String tgl2="";
      String title = "Electricity Cost Report";

      if(!MainController.startDate.equals("")){
          tgl1 = CommonUtil.formatStringDate(MainController.startDate);
          tgl2 = CommonUtil.formatStringDate(MainController.endDate);
          title = title+"\r\n"+ tgl1+"-"+tgl2;
      }

      DefaultCategoryDataset dataset1 = createDataSet1(rowValue1);
       final JFreeChart chart = ChartFactory.createBarChart3D(
            title,        // chart title
           domainAxisLabel,               // domain axis label
           rangeAxisLabel,                  // range axis label
            dataset1,                 // data
            PlotOrientation.VERTICAL,
            true,                     // include legend
            true,                     // tooltips?
            false                     // URL generator?  Not required...
        );

        chart.setBackgroundPaint(new Color(255, 255, 255));
        CategoryPlot plot = chart.getCategoryPlot();

        plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        plot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
        CategoryItemRenderer renderer1 = plot.getRenderer();
        renderer1.setSeriesPaint(0,new Color(153,51,102));
        renderer1.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.TOP_CENTER));
        renderer1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer1.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
        renderer1.setBaseItemLabelsVisible(true);




        DefaultCategoryDataset dataset2 = createDataSet2(rowValue2);
        ValueAxis axis2 = new NumberAxis3D("Unit Price (Rp)");
        //axis2.setVerticalTickLabels(true);
        //axis2.setLabelAngle(100.0);
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset2);
        plot.mapDatasetToRangeAxis(1, 1);
        CategoryItemRenderer renderer2 = new LineAndShapeRenderer();
        renderer2.setSeriesPaint(0, Color.BLUE);
        renderer2.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer2.setBaseItemLabelsVisible(true);
        plot.setRenderer(1, renderer2);

        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        NumberAxis rangeAxis = (NumberAxis)plot.getRangeAxis();
        //Set Minimum dan Maximum Value Axis
        rangeAxis.setRange(min, max);

        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());


        return chart;

  }


  private DefaultCategoryDataset createDataSet1(String rowValue) throws IOException{

     
      //String query = "from ExchangeCurrency where MONTH(date)='"+MainController.month+"' and YEAR(date)='"+MainController.year+"' order by date asc";
      List data = this.listrikDao.getAllByDate(MainController.startDate, MainController.endDate);

      DefaultCategoryDataset data1 = new DefaultCategoryDataset();
      String[] temp;
      String cat;
      double value;
      for(int i=0;i<data.size();i++){
          Listrik dt = (Listrik)data.get(i);

          temp = dt.getBulan().toString().split("-");

          cat = CommonUtil.getMonthName((Integer.parseInt(temp[1])-1));

          value = (dt.getKwh()*dt.getRpkwh()) / 1000;

          data1.addValue(value, rowValue, cat);

          System.out.println("Value : "+value+"--- bulan : "+cat);


      }

      return data1;

   }


  private DefaultCategoryDataset createDataSet2(String rowValue) throws IOException{


      //String query = "from ExchangeCurrency where MONTH(date)='"+MainController.month+"' and YEAR(date)='"+MainController.year+"' order by date asc";
      List data = this.listrikDao.getAllByDate(MainController.startDate, MainController.endDate);

      DefaultCategoryDataset data2 = new DefaultCategoryDataset();
      String[] temp;
      String cat;
      double value;
      for(int i=0;i<data.size();i++){
          Listrik dt = (Listrik)data.get(i);

          temp = dt.getBulan().toString().split("-");

          cat = CommonUtil.getMonthName((Integer.parseInt(temp[1])-1));

          value = dt.getRpkwh();

          data2.addValue(value, rowValue, cat);

          System.out.println("Value : "+value+"--- bulan : "+cat);


      }
      return data2;
    }

}